<template>
  <div class="user">
    <el-row>
      <el-col :span="24">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>用户管理</el-breadcrumb-item>
          <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <!-- 给组件绑定原生事件的话，需要一个.native的修饰符 -->
        <el-input
          placeholder="请输入内容"
          class="search-input"
          v-model="query"
          @keyup.enter="searchUsers"
          clearable
          @clear="clearVal"
        >
        </el-input>
        <el-button type="success" :icon="Search" plain @click="searchUsers"
          >Search</el-button
        >
        <el-button type="success" plain @click="addDialogFormVisible = true"
          >添加用户</el-button
        >
      </el-col>
    </el-row>
    <el-table :data="userList" border style="width: 100%" class="table" stripe>
      <el-table-column type="index" width="50"> </el-table-column>
      <el-table-column prop="username" label="姓名" width="180">
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="180"> </el-table-column>
      <el-table-column prop="mobile" label="电话"> </el-table-column>
      <el-table-column label="用户状态" width="180">
        <template #default="scope">
          <!-- {{ scope.row }} -->
          <el-switch
            v-model="scope.row.mg_state"
            class="ml-2"
            @change="changeState(scope.row)"
            style="
              --el-switch-on-color: #13ce66;
              --el-switch-off-color: #ff4949;
            "
          />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-tooltip
            class="box-item"
            effect="dark"
            content="编辑"
            placement="top"
          >
            <el-button
              size="mini"
              type="primary"
              plain
              :icon="Edit"
              @click="showEditDialog(scope.row)"
            ></el-button>
          </el-tooltip>
          <el-tooltip
            class="box-item"
            effect="dark"
            content="删除"
            placement="top"
          >
            <el-button
              size="mini"
              type="danger"
              plain
              :icon="Delete"
              @click="showDeleteDialog(scope.row)"
            ></el-button>
          </el-tooltip>
          <el-tooltip
            class="box-item"
            effect="dark"
            content="设置"
            placement="top"
          >
            <el-button
              size="mini"
              type="warning"
              plain
              :icon="Setting"
              @click="showGrantDialog(scope.row)"
            ></el-button
          ></el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <div class="page">
      <el-pagination
        v-model:current-page="pagenum"
        v-model:page-size="pagesize"
        :page-sizes="[1, 2, 5, 10]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>

  <!--  弹框 -->

  <el-dialog title="添加用户" v-model="addDialogFormVisible">
    <el-form
      :model="addForm"
      label-width="80px"
      :rules="rules"
      ref="addUserForm"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="addForm.username" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="addForm.password" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="addForm.email" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="电话" prop="mobile">
        <el-input v-model="addForm.mobile" auto-complete="off"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="addDialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAdd"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 编辑弹框 -->
  <el-dialog title="编辑用户" v-model="editDialogFormVisible">
    <el-form
      :model="editForm"
      label-width="80px"
      :rules="rules"
      ref="editUserForm"
    >
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="editForm.username"
          auto-complete="off"
          :disabled="true"
        ></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="editForm.email" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="电话" prop="mobile">
        <el-input v-model="editForm.mobile" auto-complete="off"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="editDialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="editUserSubmit('editUserForm')">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>

  <!--  分配用户角色 -->

  <el-dialog title="分配角色" v-model="grantDialogFormVisible">
    <el-form :model="grantForm" label-width="120px">
      <el-form-item label="当前的用户：" prop="username">
        <el-tag type="info">{{ grantForm.username }}</el-tag>
      </el-form-item>
      <el-form-item label="请选择角色：">
        <el-select v-model="roleId" placeholder="请选择角色">
          <el-option
            v-for="(role, index) in roleList"
            :key="index"
            :label="role.roleName"
            :value="role.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="grantDialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="grantUserSubmit()"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessage, ElMessageBox } from 'element-plus'

// import { ElMessage } from 'element-plus'
import {
  getUserList,
  getChangeState,
  addUser,
  getUserById,
  editUser,
  deleteUser,
  grantUserRole,
  getRoleList,
} from '@/api/user'

import { ref, reactive, onMounted } from 'vue'

// import { Delete, Edit, Setting, Search } from '@element-plus/icons-vue'  //引入图标
import { Delete, Edit, Avatar, Search, Setting } from '@element-plus/icons-vue'

const handleEdit = (index, row) => {
  console.log(index, row)
}
const handleDelete = (index, row) => {
  console.log(index, row)
}

const userList = ref([])

// 发送请求
const total = ref(0)
const initGetUser = async () => {
  let obj = {
    query: query.value,
    pagenum: pagenum.value,
    pagesize: pagesize.value,
  }
  let res = await getUserList(obj)
  console.log(res)
  userList.value = res.data.users
  total.value = res.data.total
  pagenum.value = res.data.pagenum
}
onMounted(() => {
  initGetUser()
})

//分页功能
const query = ref('')
const pagenum = ref(1) // 当前页
const pagesize = ref(5) // 每一页多少条
const handleSizeChange = (val) => {
  // 每一页多少条数据
  console.log('handleSizeChange', `${val} items per page`)
  pagesize.value = val
  initGetUser()
}
const handleCurrentChange = (val) => {
  // 显示的是第几页
  console.log(`current page: ${val}`)
  pagenum.value = val
  initGetUser()
}

// 搜索功能
// 1 获取到搜的内容
// 2 基于这个内容 进行发送请求
// 3 新的数据进行渲染
const searchUsers = () => {
  initGetUser()
}
// 清空搜索
const clearVal = () => {
  initGetUser()
}

// 更改用户状态
// 1 获取用户的id
// 2 获取用户最新的状态
const changeState = async (currentRow) => {
  // val 表示最新的状态
  // console.log('最新的状态', flag);
  console.log(currentRow)
  let { id, mg_state } = currentRow

  let res = await getChangeState({ uId: id, type: mg_state })
  console.log(res)
  if (res.meta.status == 200) {
    ElMessage({
      message: res.meta.msg,
      type: 'success',
      duration: 1000,
    })
  }
}

// 添加用户弹框
const addDialogFormVisible = ref(false)

// 添加用户表单数据定义
const addForm = reactive({
  username: '',
  password: '',
  email: '',
  mobile: '',
})
//表单验证
const rules = reactive({
  username: [
    {
      required: true,
      message: '请输入用户名',
      trigger: 'blur',
    },
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur',
    },
  ],
  email: [
    {
      required: true,
      message: '请输入邮箱地址',
      trigger: 'blur',
    },
    {
      type: 'email',
      message: '请输入正确的邮箱地址',
      trigger: 'blur,change',
    },
  ],
  mobile: [
    {
      required: true,
      message: '电话不能为空',
    },
    { min: 3, max: 11, message: '长度不能小于3 大于11', trigger: 'blur' },
  ],
})

// 添加用户逻辑
// 1 获取到用户的信息
// 2 发送数据
const submitAdd = async () => {
  // 结构状态和信息
  let {
    data,
    meta: { msg, status },
  } = await addUser(addForm)

  console.log(data)
  if (status == 201) {
    // 成功的提示
    ElMessage({
      message: msg,
      type: 'success',
      duration: 1000,
    })
    addDialogFormVisible.value = false
    initGetUser()
  } else {
    ElMessage({
      message: '添加失败',
      type: 'error',
      duration: 1000,
    })
  }
}

//编辑

const editDialogFormVisible = ref(false)

// 定义编辑input数据
const editForm = reactive({
  username: '',
  email: '',
  mobile: '',
  id: 0,
})
//1  打开编辑的弹框
// 2  发送请求 获取对应的数据 对应的id 获取用户信息
//3  把当前数据填充到对应的input表单里面

const showEditDialog = async (row) => {
  editDialogFormVisible.value = true // 打开弹框
  let res = await getUserById(row.id)
  console.log(res)
  if (res.meta.status == 200) {
    editForm.username = res.data.username
    editForm.email = res.data.email
    editForm.mobile = res.data.mobile
    editForm.id = res.data.id
  }
}

const editUserForm = ref(null)
//4  基于新的数据 发送请求  重新渲染页面
const editUserSubmit = () => {
  editUserForm.value.validate(async (flag) => {
    //验证是否通过
    if (flag) {
      let editUserRes = await editUser(editForm)
      console.log(editUserRes)
      if (editUserRes.meta.status === 200) {
        //编辑成功提示
        ElMessage({
          message: editUserRes.meta.msg,
          type: 'success',
          duration: 1000,
        })
        editDialogFormVisible.value = false // 关闭弹框
        // 重新刷新页面
        initGetUser()
      }
    }
  })
}

//删除
// 1 给出提示  确认要删除了那么发送请求
// 2  取消删除 那么啥都不做
// 3 删除成功了 给出成功地提示
// 4 重新加载页面
// const showDeleteDialog = (row) => {
//   ElMessageBox.confirm('亲 你真的要这样做吗 不要后悔哦?', 'Warning', {
//     confirmButtonText: '确认',
//     cancelButtonText: '取消',
//     type: 'warning',
//   })
//     .then(() => {
//       // 表示确定要删除  发送请求

//       deleteUser(row.id).then((res) => {
//         console.log(res)
//       })
//       ElMessage({
//         type: 'success',
//         message: '删除成功',
//       })
//     })
//     .catch(() => {
//       ElMessage({
//         type: 'info',
//         message: '取消删除',
//       })
//     })
// }

// 改造

const showDeleteDialog = async (row) => {
  try {
    let res1 = await ElMessageBox.confirm(
      '亲 你真的要这样做吗 不要后悔哦?',
      'Warning',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    // console.log(res1)
    // 进来了表示确认删除
    let res2 = await deleteUser(row.id)
    if (res2.meta.status === 200) {
      //删除成功提示
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
      // 重新渲染
      initGetUser()
    }
  } catch (error) {
    console.log(error)
    ElMessage({
      type: 'info',
      message: '取消删除',
    })
  }
}

// 分配权限

// 定义数据

const grantDialogFormVisible = ref(false) // 定义弹框显示与隐藏
const roleList = ref([]) // 定义角色列表

const grantForm = reactive({
  username: '',
  id: '',
})

const roleId = ref(null)
// getRoleList 获取所以的角色列表
const showGrantDialog = async (row) => {
  console.log(row.id)

  let res = await getUserById(row.id)
  console.log(res)
  grantForm.username = res.data.username
  grantForm.id = row.id

  // 获取所有的角色列表
  let res3List = await getRoleList()
  console.log(res3List)
  // 获取所有的角色列表
  roleList.value = res3List.data

  //  打开分配角色的弹框
  grantDialogFormVisible.value = true
}

//设置角色
// 1点击确认发送请求
// 2 重新更新页面

// 获取 id  rid  基于这两个id
// 获取当前的角色信息

const grantUserSubmit = async () => {
  let res2 = await grantUserRole({ id: grantForm.id, rid: roleId.value })
  console.log(res2)
  initGetUser()
  //  关闭分配角色的弹框
  grantDialogFormVisible.value = false
}
</script>

<style lang="scss" scoped>
/*element.scss中书写面包屑组件样式*/
.el-breadcrumb {
  background-color: #d3dce6;
  height: 45px;
  font-size: 15px;
  padding-left: 10px;
  line-height: 45px !important;
  margin-bottom: 15px;
}

/*组件内部style标签中书写以下样式*/
.user {
  .margin-20 {
    margin: 20px 0;
  }

  .search-input {
    width: 300px;
    margin-right: 20px;
  }

  .table {
    margin-top: 20px;
  }

  .page {
    padding: 5px 0;
    background-color: #d3dce6;
  }
}

// .el-button--text {
//     margin-right: 15px;
// }

// .el-input {
//     width: 300px;
// }

// .dialog-footer button:first-child {
//     margin-right: 10px;
// }
</style>
